package com.yangcangclub.commons.oss;

import com.alibaba.druid.util.StringUtils;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.yangcangclub.commons.config.SysConfig;
import com.yangcangclub.commons.exception.ApolloException;
import com.yangcangclub.commons.result.MessageEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
* 对OSS服务器进行上传删除等的处理
* @ClassName: OSSManageUtil
* @Description:
* @date 2016-10-18上午10:47:00
*
*/

@Component(value = "ossManageUtil")
public class OSSManageUtil {

    @Autowired
    private SysConfig sysConfig;

    private static Logger logger = LoggerFactory.getLogger(OSSManageUtil.class);

    //文件存储目录
    String filedir = "image/";
    OSSClient ossClient ;

    /**
     * 上传图片
     *
     * @param url
     */
    public void uploadImg2Oss(String url) {

        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            throw new ApolloException(MessageEnum.UPLOAD_FILE_ERROR);
        }
    }


    public String uploadImg2Oss(MultipartFile file) {
        String endpoint =sysConfig.getEndpoint();// "您的endpoint";
        // accessKey
        String accessKeyId = sysConfig.getAccessKeyId();//"您的accessKeyId";
        String accessKeySecret =sysConfig.getAccessKeySecret();// "您的accessKeySecret";
        //空间
        String bucketName = sysConfig.getBucketName();//"bcis";


         ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        if (file.getSize() > 1024 * 1024*2) { // 上传图片大小不能超过1M
            throw new ApolloException(MessageEnum.UPLOAD_FILE_TOOMAX);
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;
        } catch (Exception e) {
            throw new ApolloException(MessageEnum.UPLOAD_FILE_ERROR);
        }
    }

    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            Calendar c = Calendar.getInstance();
            String filedir1 = filedir+c.get(Calendar.YEAR)+"/"+(c.get(Calendar.MONTH) + 1) +"/"+c.get(Calendar.DAY_OF_MONTH)+"/";
            return this.getUrl(filedir1 + split[split.length - 1]);
        }
        return null;
    }

    /**
     * 上传图片返回图片地址
     * @param uploadFile
     * @return
     */
    public String uploadImg(MultipartFile uploadFile){
        String name = this.uploadImg2Oss(uploadFile);
        String url = this.getImgUrl(name);
        return  url;
    }

    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream instream, String fileName) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //空间
            String bucketName = sysConfig.getBucketName();//"bcis";

            /** 以年月日保存目录 */
            Calendar c = Calendar.getInstance();
           String filedir1 = filedir+c.get(Calendar.YEAR)+"/"+(c.get(Calendar.MONTH) + 1) +"/"+c.get(Calendar.DAY_OF_MONTH)+"/";
            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir1 + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public   String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase("jpeg") ||
                FilenameExtension.equalsIgnoreCase("jpg") ||
                FilenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase("pptx") ||
                FilenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase("docx") ||
                FilenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        //空间
        String bucketName = sysConfig.getBucketName();//"bcis";

        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            String res = url.toString();
            String[] urlArray = res.split("\\?");
            return urlArray[0];
        }
        return null;
    }

    /**
     * 根据key删除OSS服务器上的文件
     * @Title: deleteFile
     * @Description:
     * @param @param ossConfigure
     * @param @param filePath    设定文件
     * @return void    返回类型
     * @throws
     */
    public   void deleteFile(SysConfig ossConfigure,String filePath){
        ossClient = new OSSClient(ossConfigure.getEndpoint(),ossConfigure.getAccessKeyId(), ossConfigure.getAccessKeySecret());
        ossClient.deleteObject(ossConfigure.getBucketName(), filePath);

    }


}
